<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>二维码登录</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <!-- jquery -->
    <script type="text/javascript" th:src="@{/js/jquery.min.js}"></script>
</head>
<body>
    <div class="qrCodeImg-box" id="qrImgDiv"></div>
</body>
<script>
    $(function(){
        initQrImg();
    });

    // 定义api、ws地址
    var path = "://localhost:8888";
    var getQrPath = "http" + path + "/qr/getLoginQr";
    var wsPath = "ws" + path + "/qrSocket/";

    /**
     * 初始化二维码
     */
    function initQrImg(){
        // 清空二维码
        $("#qrImgDiv").empty();

        // 定义XMLHttpRequest
        var xmlHttp;
        xmlHttp=new XMLHttpRequest();
        xmlHttp.open("GET",getQrPath,true);
        xmlHttp.responseType = "blob";

        xmlHttp.onload = function(){
            console.log(this);
            uuid = this.getResponseHeader("uuid");
            if (this.status == 200) {
                var blob = this.response;
                var img = document.createElement("img");
                img.className = 'qrCodeBox-img';
                img.onload = function(e) {
                    window.URL.revokeObjectURL(img.src);
                };
                img.src = window.URL.createObjectURL(blob);
                document.getElementById("qrImgDiv").appendChild(img);

                // 建立webSocket连接
                initWebSocket();
            }

        }

        // 发起请求
        xmlHttp.send();

    }

    /**
     * 建立webSocket连接
     */
    function initWebSocket(){
        if(typeof(WebSocket) == "undefined") {
            console.log("您的浏览器不支持WebSocket");
        }else{
            console.log("您的浏览器支持WebSocket");
            var wsPathStr = wsPath+uuid;
            var socket = new WebSocket(wsPathStr);
            // 打开事件
            socket.onopen = function() {
                console.log("Socket 已打开");
            };

            // 关闭事件
            socket.onclose = function() {
                console.log("Socket已关闭");
            };

            //发生了错误事件
            socket.onerror = function() {
                alert("Socket发生了错误");
            }

            //获得消息事件
            socket.onmessage = function(msg) {
                console.log(msg.data);
                var data = JSON.parse(msg.data);
                if(data.code == 200){
                    alert("登录成功！");
                    //这里存放自己业务需要的数据。怎么放自己看
                    window.sessionStorage.uuid = uuid;
                    window.sessionStorage.userId = data.userId;
                    window.sessionStorage.projId = data.projId;

                    window.location.href = "http://localhost:8888/kf/index/ie"
                }else{
                    //如果过期了，关闭连接、重置连接、刷新二维码
                    socket.close();
                    initQrImg();
                }
                //发现消息进入    开始处理前端触发逻辑
            };
        }
    }
</script>
</html>